package app.model.proxies
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.OutputProgressEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	import org.puremvc.as3.multicore.patterns.proxy.Proxy;

	public class OutProxy extends Proxy
	{
		public static const NAME:String = "OutProxy";
		
		public static const DATA_OUT_LOAD_COMPLETE:String = "dataOut/load/complete";
		public static const DATA_OUT_LOAD_FAILURE:String = "dataOut/load/failure";
		public static const DATA_OUT_LOAD_PROGRESS:String = "dataOut/load/progress";
		
		private var file:File;
		private var fileStream:FileStream;
		
		public function OutProxy()
		{
			super(NAME);
		}
		
		
		public function persist( url:String, data:Object ):void{
			file = new File( url );
			fileStream = new FileStream ( );
			fileStream.addEventListener( OutputProgressEvent.OUTPUT_PROGRESS, onProgress );
			fileStream.addEventListener( IOErrorEvent.IO_ERROR, onError );
			fileStream.openAsync( file, FileMode.WRITE );
			fileStream.writeUTFBytes( data.toString() );			
		}		
		
		private function reset():void{
			file = null;
			fileStream.removeEventListener( OutputProgressEvent.OUTPUT_PROGRESS, onProgress );
			fileStream.removeEventListener( IOErrorEvent.IO_ERROR, onError );
			fileStream.close();
			fileStream = null;
		}
		
		
		private function onError(event:Event):void{
			sendFailNote( event );
			reset();
		}
		
		private function onProgress( event:OutputProgressEvent ):void {
			if( event.bytesPending == 0){
				sendProgressNote( event );
				sendCompleteNote(  );
				reset();
			}else{
				sendProgressNote( event );
			}
			
		}
		
		private function sendCompleteNote(  ):void{
			sendNotification(DATA_OUT_LOAD_COMPLETE, null, file.url);
		}
		
		private function sendFailNote( event:Event ):void{
			sendNotification(DATA_OUT_LOAD_FAILURE, event);
		}
		
		private function sendProgressNote( event:Event ):void{
			sendNotification(DATA_OUT_LOAD_PROGRESS, event);
		}
		
		
	}
}